<?php

namespace App\Http\Controllers\Front;

use App\Model\Common;
use App\Model\UserActivity;
use App\Model\UserBonusCount;
use App\Model\UserDetail;
use App\Model\UserInviteOneYuan;
use App\Model\UserSalesmanBonusCount;
use App\Model\UserSalesmanInviteOneYuan;
use App\Model\WeChat;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserActivityController extends Controller
{

    private $user;

    public function __construct ()
    {
        $this->user = \Auth::user();
    }

    // 获取活动海报信息
    public function getPosterUserInfo(Request $request)
    {
        $user = $request->user();

        // todo 有海报
        $userActivity = UserActivity::where("user_id", $user->id)->first();
        $is_ac = false;
        if ($userActivity){
            $is_ac = $userActivity->media;
        }
        $user_detail = UserDetail::where('user_id', $user->id)->first();
        $weChat = new  WeChat();
        if ($user->qr_code) {
            $qr_code = $user->qr_code;
        } else {
            $qr_code = $weChat->saveHeadPortrait($user_detail, $user_detail->head_portrait, 200);
        }

        $img= Common::curl_file_get_contents($user_detail->head_portrait);
        $imgName = \Illuminate\Support\Str::random(16) . time() . $user_detail->user_id . '.jpg';
        $imgPath = base_path('public') . '/' . $imgName;
        file_put_contents($imgPath, $img);
        $base = $this->imgToBase64($imgPath);
        unlink(public_path($imgName));
        $str = str_replace(env('apiUrl'), '',$qr_code);
        $base_qr_code = $this->imgToBase64(public_path($str));
        return $this->renderJson([
            'head_portrait' => $base,
            'wechat_name' => $user_detail->wechat_name,
            'qr_code' => $base_qr_code,
            'is_ac'=>$is_ac
        ]);
    }

    // 生成海报活动
    public function savePoster(Request $request)
    {
        $user = $request->user();
        $path = $request->input('path');
        $local_path = str_replace(env('apiUrl'), '', $path);
        // 重复进入
        $user_activity = UserActivity::where("user_id", $user->id)->first();
        $weChat = new  WeChat();
        if ($user_activity){
            if (!empty($user_activity->media_id) || $user_activity->media_id != "" || trim($user_activity->media_id) != ""){
                \Log::info ($user_activity->media_id);
                \Log::info (11);
                return $this->success();
            }else{
                // 领取了2元进入
                $media_id = $weChat->uploadWeChatImg(public_path($local_path));
                $user_activity->media_id = $media_id;
                $user_activity->media_path = $local_path;
                $user_activity->media = $path;
                $user_activity->save();
            }
        }else{
            // 直接进入
            $media_id = $weChat->uploadWeChatImg(public_path($local_path));
            $activity  = new UserActivity();
            $activity->user_id = $user->id;
            $activity->keyword = '海报';
            $activity->type = 1;
            $activity->media_id = $media_id;
            $activity->media_path = $local_path;
            $activity->media = $path;
            $activity->save();
        }
        return $this->success();
    }

    /**
     * 注册领取营销奖励
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function saveUserActivityBill(Request $request)
    {
        $activity =  UserActivity::whereUserId($this->user->id)->first();
        if($activity){
            return $this->success();
        }
        try{
            \DB::beginTransaction();
            $user_activity = new UserActivity();
            $user_activity->user_id = $this->user->id;
            $user_activity->type = 1;
            $user_activity->save();
            // 一元活动的添加
            try{
                if ($this->user->type == 4){
                    $user_invite_one_yuan = new  UserInviteOneYuan();
                    $user_invite_one_yuan->money = 1;
                    $user_invite_one_yuan->title = "活动奖励金";
                    $user_invite_one_yuan->content = "注册活动奖金";
                    $user_invite_one_yuan->user_id = $this->user->id;
                    $user_invite_one_yuan->save();
                    // 记录营销奖励金总表
                    $user_bonus_count  = new UserBonusCount();
                    $user_bonus_count->type = 2;
                    $user_bonus_count->income_type = 1;
                    $user_bonus_count->user_id = $this->user->id;
                    $user_bonus_count->money = 1;
                    $user_bonus_count->relation_id = $user_invite_one_yuan->id;
                    $user_bonus_count->describe = "注册活动奖金";
                    $user_bonus_count->save();
                }else{
                    $user_salesman_invite_one_yuan = new UserSalesmanInviteOneYuan();
                    $user_salesman_invite_one_yuan->money = 1;
                    $user_salesman_invite_one_yuan->title = "活动奖励金";
                    $user_salesman_invite_one_yuan->content = "注册活动奖金";
                    $user_salesman_invite_one_yuan->user_id = $this->user->id;
                    $user_salesman_invite_one_yuan->save();
                    // 记录营销奖励金总表
                    $user_salesman_bonus_count = new UserSalesmanBonusCount();
                    $user_salesman_bonus_count->type = 2;
                    $user_salesman_bonus_count->income_type = 1;
                    $user_salesman_bonus_count->user_id = $this->user->id;
                    $user_salesman_bonus_count->money = 1;
                    $user_salesman_bonus_count->relation_id = $user_salesman_invite_one_yuan->id;
                    $user_salesman_bonus_count->describe = "注册活动奖金";
                    $user_salesman_bonus_count->save();

                }
                \DB::commit();
            }catch (\Exception $exception){
                \DB::rollBack ();
                \Log::error ($exception);
                return $this->fail ("领取失败！");
            }

            $this->user->increment('currentCommission', $request->input("amount"));
            $this->user->increment('rewards_all', $request->input("amount"));

        }catch (\Exception $e){
            \DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success();
    }

   public function imgToBase64($img_file) {

        $img_base64 = '';
        if (file_exists($img_file)) {

            $app_img_file = $img_file; // 图片路径
            $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等

            //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
            $fp = fopen($app_img_file, "r"); // 图片是否可读权限

            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $file_content = chunk_split(base64_encode($content)); // base64编码
                switch ($img_info[2]) {           //判读图片类型
                    case 1: $img_type = "gif";
                        break;
                    case 2: $img_type = "jpg";
                        break;
                    case 3: $img_type = "png";
                        break;
                }
                $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码
            }
            fclose($fp);
        }

        return $img_base64; //返回图片的base64
    }

}
